﻿//  

#region

using Microsoft.Practices.Unity.StaticFactory;
using Microsoft.Practices.Unity.TestSupport;
using Microsoft.VisualStudio.TestTools.UnitTesting;

#endregion

namespace Microsoft.Practices.Unity.Tests
{
    /// <summary>
    /// Tests for the Static Factory container extension.
    /// </summary>
    [TestClass]
    public class StaticFactoryFixture
    {
        [TestMethod]
        public void CanAddExtensionToContainer()
        {
            var container = new UnityContainer()
                .AddNewExtension<StaticFactoryExtension>();
        }

        [TestMethod]
        public void CanGetExtensionConfigurationFromContainer()
        {
            var container = new UnityContainer()
                .AddNewExtension<StaticFactoryExtension>();

            var config = container.Configure<IStaticFactoryConfiguration>();

            Assert.IsNotNull(config);
        }

        [TestMethod]
        public void ConfiguredFactoryDelegateGetsCalled()
        {
            var factoryWasCalled = false;

            var container = new UnityContainer()
                .AddNewExtension<StaticFactoryExtension>()
                .Configure<IStaticFactoryConfiguration>()
                .RegisterFactory<MockLogger>(
                delegate
                    {
                        factoryWasCalled = true;
                        return new MockLogger();
                    })
                .Container
                .RegisterType<ILogger, MockLogger>();

            var logger = container.Resolve<ILogger>();
            Assert.IsInstanceOfType(logger, typeof (MockLogger));
            Assert.IsTrue(factoryWasCalled);
        }

        [TestMethod]
        public void CanUseContainerToResolveFactoryParameters()
        {
            var factoryWasCalled = false;
            var connectionString = "Northwind";

            IUnityContainer container = new UnityContainer();

            container.AddNewExtension<StaticFactoryExtension>()
                .Configure<IStaticFactoryConfiguration>()
                .RegisterFactory<MockDatabase>(
                delegate(IUnityContainer c)
                    {
                        Assert.AreSame(container, c);
                        factoryWasCalled = true;
                        var cs = c.Resolve<string>("connectionString");
                        return MockDatabase.Create(cs);
                    })
                .Container
                .RegisterInstance("connectionString", connectionString);

            var db = container.Resolve<MockDatabase>();

            Assert.IsTrue(factoryWasCalled);
            Assert.IsNotNull(db);
            Assert.AreEqual(connectionString, db.ConnectionString);
        }
    }
}